package cn.jtool.dig.client.comm;

import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.netty.TcpClient;
import cn.jtool.dig.common.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 消息交换管理器
 */
@Slf4j
public class MessageExchange {


    /**
     * 外转发Servre发送数据
     * @param packet
     */
    public static void toReal(Packet packet) {
        TcpClient relayClient = SpringContextUtil.getBean("tunnelClient", TcpClient.class);
        if (relayClient.isRunning()){
            try {
                relayClient.getChannel().writeAndFlush(packet);
            } catch (InterruptedException e) {
                log.error("发送数据到RelayServer异常, {}", packet);
            }
        }
    }

    /**
     * 向三方平台发送数据
     * @param packet
     */
    public static boolean toVirtual(Packet packet){
        TcpClient client = VirtualManager.getClient(packet.getHeader().getChannelId());
        if(Objects.isNull(client)){
            return false;
        }
        if (client.isRunning()) {
            try {
                client.getChannel().writeAndFlush(packet.getBody().getBytes());
                return true;
            } catch (InterruptedException e) {
                log.error("发送数据到三方异常, {}", packet);
            }
        }
        return false;
    }

}
